package com.itmck.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itmck.dto.response.ApiResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 太阳当空照,花儿对我笑
 * <p>
 * Create by M ChangKe 2021/11/4 14:57
 * <p>
 * 自定义全局sentinel异常处理
 * <p>
 **/
@Slf4j
@Component
public class SentinelBlockHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {

        log.info("BlockExceptionHandler BlockException================" + e.getRule());
        ApiResultResponse<String> resp;
        // 不同的异常返回不同的提示语
        if (e instanceof FlowException) {
            resp = ApiResultResponse.error("接口限流", "4001");
        } else if (e instanceof DegradeException) {
            resp = ApiResultResponse.error("服务降级", "4002");
        } else if (e instanceof ParamFlowException) {
            resp = ApiResultResponse.error("热点参数限流", "4003");
        } else if (e instanceof SystemBlockException) {
            resp = ApiResultResponse.error("触发系统保护规则", "4004");
        } else if (e instanceof AuthorityException) {
            resp = ApiResultResponse.error("授权规则不通过", "4005");
        } else {
            resp = ApiResultResponse.error("系统异常", "500");
        }
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(response.getWriter(), resp);
    }
}